package wangjg.commons.compress;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 
 * @author wangjg
 */
public class Zip {

	public void zip(String zipFileName, String inputFilePath) throws IOException {
		ZipOutputStream out = null;
		try {
			out = new ZipOutputStream(new FileOutputStream(zipFileName));
			zip(out, new File(inputFilePath), "");
		}finally{
			try {
				if(out!=null)out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void zip(ZipOutputStream out, File inputFile, String base) throws IOException {
		System.out.println("Zipping  " + inputFile.getName());
		if (inputFile.isDirectory()) {
			base += inputFile.getName()+"/";
			out.putNextEntry(new ZipEntry(base));
			File[] fl = inputFile.listFiles();
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base);
			}
		} else {
			out.putNextEntry(new ZipEntry(base+inputFile.getName()));
			FileInputStream in = new FileInputStream(inputFile);
			try{
				int len = 0;
				byte[] buf = new byte[1024];
				while ((len = in.read(buf)) != -1){
					out.write(buf,0,len);
				}
			}finally{
				if(in!=null)
					in.close();
			}
		}

	}

	public void unzip(String zipFileName, String outputDirectory) throws IOException {
		ZipInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new ZipInputStream(new FileInputStream(zipFileName));
			ZipEntry zipEntry;
			while ((zipEntry = in.getNextEntry()) != null) {
				if (zipEntry.isDirectory()) {
					String name = zipEntry.getName();
					name = name.substring(0, name.length() - 1);
					File f = new File(outputDirectory + File.separator + name);
					f.mkdir();
				} else {
					File file = new File(outputDirectory + File.separator + zipEntry.getName());
					out = new FileOutputStream(file);
					int len = 0;
					byte[] buf = new byte[512];
					while ((len = in.read(buf)) != -1) {
						out.write(buf, 0, len);
					}
					out.close();
				}
			}
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (out != null)
					out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
